package org.ephone;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import android.app.Application;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
/*
 * Firstly I've supposed a buffer
 * */
public class ePhoneApp extends Application {
	
    public TelephonyManager mTelMgr;
    public PhoneStateListener mListener;
	
	private ReentrantLock lock = new ReentrantLock();
	private Condition notEmptyCond = lock.newCondition();
	private boolean full = false;
	//private int lastUsedIndex = -1;
	//private String command[] = {"", "", ""};
	private String command = "";
	Toast test;
	
	public void prepareTelManager(){
		mTelMgr = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
	}
	
	public String getCommand() throws Exception{
		//String[] result = new String[3];
		String result = "";
		//test = Toast.makeText(getApplicationContext(), command.toString(), Toast.LENGTH_LONG);
		lock.lock();
		try{
			while(/*lastUsedIndex == -1*/!full){
				notEmptyCond.await();
			}
			/*
			for(int i = 0; i < 1; i++){
				result[i] = command[i]; 
				command[i] = "";
			}
			*/
			result = command;
			command = "";
			
			full = false;
		} finally {
			lock.unlock();
		}
		
		//test = Toast.makeText(getApplicationContext(), command.toString(), Toast.LENGTH_LONG);
		//test.show();
		return result;
	}
	
	public void setCommand(String input){
		lock.lock();
		/*
		if (lastUsedIndex < 2){
			lastUsedIndex++;
			command[lastUsedIndex] = input;
		} else {
			command[2] = command[1];
			command[1] = command[0];
			command[0] = input;
			lastUsedIndex = -1;
		}
		*/
		//command[0] = input;
		command = input;
		full = true;
		try {
			notEmptyCond.signalAll();
		} finally {
			lock.unlock();
		}
	}
}
